<?php
/*!
LoginController
EXTENDS Zend_Controller_Action

*/
class LoginController extends Zend_Controller_Action
{
	
    public function init()
    {	
		//! Initializes model for user.\n
		//! Initializes redirector for page redirects.\n
		
		$this->userModel = new Application_Model_Login();
		$this->_redirector = $this->_helper->getHelper('Redirector');
    }

    public function indexAction()
    {
		//! Creates/Accesses 'user' namespace.\n
		//! Calls getForm().\n
		//! Returns /login action IF username == NOT NULL.\n
		
		$user=new Zend_Session_Namespace('user');
		if ($user->username != "")
			$this->_redirector->gotoUrl('/index');
		$this->view->form=$this->getForm();
    }
	
    public function getForm() 
    {
		//! Gets Application_Form_Login().\n
		
    	return new Application_Form_Login(array('action'=>'/login/process','method'=>'post'));
    }
    
    public function loginAction()
    {
		//! Calls user model.\n
		//! Creates/accesses 'user' namespace.\n
		//! Creates/accesses 'login_session' namespace.\n
		//! Queries POST data with user model.\n
		//! Stores query results in 'user' namespace.\n
		//! Sets 'login_session' end_seconds.\n
		//! Returns /login/login action.\n
		
    	$username = $_POST['username'];
		$password = md5($_POST['password']);
		$userModel = $this->userModel;
		$match = $userModel->userExists($username,$password);
		
		//if user exists, load user
		if ($match == true) {
			$curruser = new Zend_Session_Namespace('user');
			$curruser->username = $username;
			$curruser->role = $userModel->getRole($username);
			
			//login timestamp
			$login_session = new Zend_Session_Namespace('login_session');
			$login_session->start_time = time();
			$login_session->check_time = time();
			$login_session->end_seconds = 1800;
			
			$this->_redirector->gotoUrl('/index');
		}		
    }
}



